#!/usr/bin/env python
from __future__ import with_statement #for comapatibility with Python 2.5
import os
import sys
from subprocess import Popen
import re
import fnmatch
from getopt import getopt
from contest.util import *
from contest.monitor import monitor_name, mainloop
from contest.printer import VerbosePrinter
from contest.sound import nosound, quack

test_cmd_args = [sys.executable, '-m', 'contest.runtests']
src_pattern = PYTHON_SRC_PATTERN
walker = os.walk
beep = nosound

# python -m contest.main -R -f t.c sh -c 'gcc t.c && ./a.out'
opts, args = getopt(sys.argv[1:], '1:f:F:rq')
recursive = True
for o, a in opts:
    if o == '-F':
        # file-match pattern (regex)
        src_pattern = re.compile(a)
    if o == '-f':
        # file-match pattern (shell style pattern)
        src_pattern = re.compile('^' + fnmatch.translate(a))
    if o == '-1':
        assert monitor_name == 'fallback'
        src_pattern = a
    if o == '-r':
        recursive = False
    if o == '-q':
        beep = quack()
if args:
    test_cmd_args = args

def runtests():
    p = Popen(test_cmd_args, stdout=sys.stdout, stderr=sys.stderr)
    try:
        p.wait()
    except KeyboardInterrupt:
        pass
    finally:
        # It's okay to call wait() more than once. Really?
        try:
            retcode = p.wait()
        except OSError:
            retcode = 0
    return retcode

class Run:
    def __init__(self, printer):
        self.printer = printer
    def __call__(self):
        self.printer.before_run()
        rc = runtests()
        if rc != 0:
            beep()
        self.printer.after_run(rc)

def main(pattern, recursive=True):
    printer = VerbosePrinter()
    print('Using '+monitor_name+' monitor')
    run = Run(printer)
    mainloop(os.curdir, pattern, run, recursive)

if __name__ == '__main__':
    try:
        main(src_pattern, recursive=recursive)
    except KeyboardInterrupt:
        pass
